// TCPClient project main.go
package monitor

import (
    "fmt"
    "os"
    "time"
)

type Monitor struct {
	region Region
	pg PgInfo
	c Cconn
	cmdch chan []byte
	pgch chan []byte
	logf DataFile
	exitflag bool
}


type PgInfo struct {
	//cmdType 	uint8
	//cmdBit 	uint8
	cmdLv 		uint8
	logicAddr	[6]byte
	swSta		uint8
	emFlag		uint8
	//volCH		uint8
	pgId		uint16
	lastPgid	uint16
	playwcnt    int
	cmdwcnt     int
}


func (pg *PgInfo) Pginfo() string{
	p := pg.logicAddr
	var em string
	if pg.emFlag == 1 {
		em = "应急"
	}else {
		em = "普通"
	}
	return fmt.Sprintf("[%d，%02X%02X%02X%02X%02X%02X，%s]", pg.pgId, p[0],p[1],p[2],p[3],p[4],p[5], em) 
}

func (m *Monitor)PgStart() {
	var buf [3]byte
	buf[0] = 0x0A
	buf[1] = uint8(m.pg.pgId >> 8)
	buf[2] = uint8(m.pg.pgId&0xff)
	filename := m.logf.Mp3Open(m.region.Name)
	m.logf.WriteLogln("节目开始", m.pg.Pginfo())
	m.logf.WriteLogln("开始保存mp3文件：", filename)
	m.pgch <- buf[0:] 
}

func (m *Monitor)PgStop() {
	var stop = [3]byte{0x0b, 0x00, 0x00}
	m.pg.pgId = 0
	m.pg.lastPgid = 0
	m.logf.Mp3Close()
	m.logf.WriteLogln("节目停止")
	m.pgch <- stop[:]
}


func (m *Monitor) player_manage() {
	if m.pg.playwcnt > 0{
		m.pg.playwcnt-- 
		if m.pg.playwcnt == 0 {
			m.logf.WriteLogln("节目心跳超时", m.pg.Pginfo())
			m.pg.CmdStop()
			m.PgStop()
		}
	}
	
	if m.pg.cmdwcnt > 0{
		m.pg.cmdwcnt-- 
		if m.pg.cmdwcnt == 0 {
			m.logf.WriteLogln("指令心跳超时", m.pg.Pginfo())
			m.pg.CmdStop()
			m.PgStop()
			m.exitflag = true
		}
	}
	
	current_id := m.pg.pgId
	
	if current_id != 0 && m.pg.lastPgid == 0 {
		m.PgStart()
	}else if current_id == 0 && m.pg.lastPgid != 0 {
		m.PgStop()
	}else if current_id != 0 && m.pg.lastPgid != current_id {
		m.PgStop()
		m.PgStart()
	}
	m.pg.lastPgid = current_id

	IdbgCmd(4, "cmdwcnt=", m.pg.cmdwcnt)
}

func (m *Monitor) Monitor() {
	var pg Bconn
	cmdip := m.region.CmdIp
	pgip := m.region.PgIp
	m.logf.LogOpen(m.region.Name)
	defer m.logf.LogClose()
	
	m.logf.WriteLogln("系统初始化完成")

	m.cmdch = make(chan []byte, 2)
	go m.RunCmd(cmdip, m.cmdch)
	
	m.pgch = make(chan []byte, 2)
	go pg.RunPg(pgip, m.pgch, &m.logf)

	hearttick := time.Tick(1000 * time.Millisecond)
	//logRenameTick := time.Tick(60 * time.Second)
	for {
        select {
        case <-hearttick: 
			m.player_manage()
			
//		case <-logRenameTick: 
//			m.logf.LogOpen(m.region.Name)
        }
    }
	//can't run here
    os.Exit(0)
}

func  Server() {
	var ma [20]Monitor
	for n, d := range UserCfg.Regions {
		if n > 9 {
			fmt.Println("max 20 monitor")
			break
		}
		if d.Enabled {
			head := fmt.Sprintf("%02d_", n)
			d.Name = head + d.Name
			ma[n].logf.LogInit(d.WriteLogEable, d.WriteMp3Eable)
			ma[n].region = d
			go ma[n].Monitor()
		}
	} 
	for {
		time.Sleep(time.Second * 1)
	}
}





